package com.yuntu.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuntu.api.aliyunai.AliYunAiApi;
import com.yuntu.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.yuntu.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yuntu.demo.constant.UserConstant;
import com.yuntu.demo.dto.file.UploadPictureResult;
import com.yuntu.demo.dto.picture.*;
import com.yuntu.demo.entity.Picture;
import com.yuntu.demo.entity.Space;
import com.yuntu.demo.entity.User;
import com.yuntu.demo.enums.PictureReviewStatusEnum;
import com.yuntu.demo.vo.LoginUserVO;
import com.yuntu.demo.vo.PictureVO;
import com.yuntu.demo.vo.UserVO;
import com.yuntu.exception.ErrorCode;
import com.yuntu.exception.ThrowUtils;
import com.yuntu.exception.bizException;
import com.yuntu.manager.CosManager;
import com.yuntu.manager.upload.FilePictureUpload;
import com.yuntu.manager.upload.PictureUploadTemplate;
import com.yuntu.manager.upload.UrlPictureUpload;
import com.yuntu.mapper.PictureMapper;
import com.yuntu.service.IPictureService;
import com.yuntu.service.ISpaceService;
import com.yuntu.service.IUserService;
import com.yuntu.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 图片 服务实现类
 * </p>
 *
 * @author k
 * @since 2025-03-20
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements IPictureService {

    @Resource
    FilePictureUpload filePictureUpload;
    @Resource
    UrlPictureUpload urlPictureUpload;
    @Resource
    IUserService userService;
    @Autowired
    private CosManager cosManager;
    @Resource
    ISpaceService spaceService;
    @Resource
    TransactionTemplate transactionTemplate;
    @Autowired
    private AliYunAiApi aliYunAiApi;

    @Override
    public PictureVO uploadPicture(Object inputSorce, PictureUploadRequest pictureUploadRequest, LoginUserVO loginUser) {
        //新增还是更新图片（有id的是新增）
        Long picturId=pictureUploadRequest==null?null:pictureUploadRequest.getId();
        //如果上传文件有指定spaceid-》只有本人能在私有空间上传文件
        Long spaceId = pictureUploadRequest.getSpaceId();
        if(spaceId!=null){
            //判断是否是本人
            Space space = spaceService.getById(spaceId);
           ThrowUtils.throwIf(space==null,ErrorCode.PARAMS_ERROR,"该空间不存在");
//            if(!space.getUserId().equals(loginUser.getId())){
//                throw new bizException(ErrorCode.NO_AUTH_ERROR,"没有空间权限");
//            }
            //校验额度是否充足
            Long maxSize = space.getMaxSize();
            Long maxCount = space.getMaxCount();
            Long totalCount = space.getTotalCount();
            Long totalSize = space.getTotalSize();
            if(totalCount>=maxCount){
                throw new bizException(ErrorCode.OPERATION_ERROR,"存储条数不足");
            }
            if(totalSize>=maxSize){
                throw new bizException(ErrorCode.OPERATION_ERROR,"空间容量不足");
            }
        }
        //如果是更新图片，校验图片是否存在
        Picture oldPicture=null;
        if (picturId != null) {
            oldPicture = this.getById(picturId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅本人或管理员可编辑
//            if (!oldPicture.getUserId().equals(loginUser.getId()) && !loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
//                throw new bizException(ErrorCode.NO_AUTH_ERROR);
//            }
            //更新图片-》空间需要一致
            if(spaceId==null){
                //没有设置，直接设置为旧的
                spaceId=oldPicture.getSpaceId();
            }else{
                //判断是否时同一个空间
                ThrowUtils.throwIf(!spaceId.equals(oldPicture.getSpaceId()),ErrorCode.PARAMS_ERROR,"空间id不一致");
            }
        }
        String uploadPrefix="";
        if(spaceId==null){
            uploadPrefix= String.format("public/%s",loginUser.getId());
        }else{//如果有空间，按空间存储
            uploadPrefix= String.format("public/%s",spaceId);
        }
        //根据传过来的类型判断传到哪个类
        PictureUploadTemplate pictureUploadTemplate =filePictureUpload;
        if(inputSorce instanceof String) {
            pictureUploadTemplate=urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSorce, uploadPrefix);
        //上传图片，得到图片信息，根据用户id放不同文件夹
        Picture picture=new Picture();
        // 构造要入库的图片信息
        picture.setUrl(uploadPictureResult.getUrl());
        //将缩略图路径加入
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setPicColor(uploadPictureResult.getPicColor());
        //将spaceid加入
        picture.setSpaceId(spaceId);
        //构造图片信息（更新将id加上）
        if(picturId!=null){
            picture.setId(picturId);
            //更新编辑时间，更新时间数据库自动更新
            picture.setEditTime(LocalDateTime.now());
        }
        //填充审核信息
        this.fillReviewParams(picture,loginUser);
        //加入数据库,开启事务
        transactionTemplate.execute(status -> {
            boolean save = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR);
            //上传之后，增加已经使用的空间
            //上传到私有空间执行
            if(picture.getSpaceId()!=null){
                boolean update = spaceService.lambdaUpdate().eq(Space::getId, picture.getSpaceId())
                        .setSql("totalSize=totalSize+"+picture.getPicSize())
                        .setSql("totalCount=totalCount+1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.SYSTEM_ERROR);
            }
            return null;
        });
        //如果是更新图片，删除原来的图
//        if(picturId!=null){
//            deletePicture(oldPicture);
//        }
        return PictureVO.objToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        //获取起始结束时间
        LocalDateTime startEditTime = pictureQueryRequest.getStartEditTime();
        LocalDateTime endEditTime = pictureQueryRequest.getEndEditTime();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        //添加起始结束时间
        queryWrapper.ge(ObjectUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.le(ObjectUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        //添加审核相关条件的生成
        //只有是公共空间才判断审核条件
        if(spaceId==null){
            Integer reviewStatus = pictureQueryRequest.getReviewStatus();
            String reviewMessage = pictureQueryRequest.getReviewMessage();
            Long reviewerId = pictureQueryRequest.getReviewerId();
            queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
            queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
            queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        }
        //加上空间id-》spaceid为空-》查公共图库
        queryWrapper.eq(spaceId!=null, "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId,"spaceId");
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }
    /**
     * 分页获取图片封装为vo
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        Page<PictureVO> voPage=new Page<>(picturePage.getCurrent(),picturePage.getSize(),picturePage.getTotal());
        List<Picture> pictures = picturePage.getRecords();
        //将records转换为vo
        List<PictureVO> pictureVOS=new ArrayList<>();
        pictures.forEach(picture -> {
            pictureVOS.add(PictureVO.objToVo(picture));
        });
        //vo设置user
        //查对应的user
        pictureVOS.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        });
        voPage.setRecords(pictureVOS);
        return voPage;
    }
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }



    /**
     * 审核图片
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        if(pictureReviewRequest==null){
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        //判断传过来的参数是否合法
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        Long id = pictureReviewRequest.getId();
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        PictureReviewStatusEnum enumByValue = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        //参数为空或传过来的审核为未审核状态（无意义）
        if(id==null||reviewStatus==null||enumByValue.equals(PictureReviewStatusEnum.REVIEWING)){
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        //加入数据库
        Picture picture = this.getById(id);
        if(picture==null){
            throw new bizException(-1,"图片不存在");
        }
        //如果审核状态和已存状态一致-》无意义
        if (picture.getReviewStatus().equals(reviewStatus)) {
            throw new bizException(ErrorCode.PARAMS_ERROR,"请勿重复审核");
        }
        //直接用查出来的字段，所有字段都会更新，所以用新的picture,只需更改改了的值
        Picture rePicture=new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, rePicture);
        rePicture.setReviewTime(LocalDateTime.now());
        rePicture.setReviewerId(loginUser.getId());
        boolean b = this.updateById(rePicture);
        ThrowUtils.throwIf(!b, ErrorCode.SYSTEM_ERROR);
    }
    @Override
    public void fillReviewParams(Picture picture, LoginUserVO loginUser) {
        if (loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(LocalDateTime.now());
        } else {
            // 非管理员，创建或编辑都要改为待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, LoginUserVO loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多 30 条");
        // 要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new bizException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new bizException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements imgElementList = div.select("img.mimg");
        int uploadCount = 0;
        //获取批量上传的文件前缀
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if(StrUtil.isBlank(namePrefix)){//如果没给前缀，使用搜索名
            namePrefix=pictureUploadByBatchRequest.getSearchText();
        }
        for (Element imgElement : imgElementList) {
            String fileUrl = imgElement.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空，已跳过: {}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setPicName(namePrefix+(uploadCount+1));
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        log.info(String.valueOf(uploadCount));
        return uploadCount;
    }
    /**
     * 清理对象存储中的图片
     * @param picture
     */
    public void deletePicture(Picture picture){
        //判断该图片是否只有一个用户使用
        String oldUrl = picture.getUrl();
        Long count = lambdaQuery().eq(Picture::getUrl, oldUrl).count();
        if(count>0){//数据库中还有此url
            return;
        }
        //清理压缩图
            cosManager.deleteObject(oldUrl);
            //清理缩略图
            if(StrUtil.isNotBlank(picture.getThumbnailUrl())){
                cosManager.deleteObject(picture.getThumbnailUrl());
            }
    }
    @Override
    public void checkPictureAuth(LoginUserVO loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new bizException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new bizException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }
    @Override
    public void deletePicture(long pictureId, LoginUserVO loginUser) {
        ThrowUtils.throwIf(loginUser==null,ErrorCode.PARAMS_ERROR);
        //查出数据
        Picture picture = this.lambdaQuery().eq(Picture::getId, pictureId).one();
        ThrowUtils.throwIf(picture==null,ErrorCode.SYSTEM_ERROR);
        //判断权限-》仅本人或管理员可进行删除
        this.checkPictureAuth(loginUser, picture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            //删除
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = picture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + picture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        this.deletePicture(picture);
    }
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, LoginUserVO loginUser) {
        //先判断是否有该图片
        if(pictureEditRequest.getId()==null){
            throw new bizException(ErrorCode.PARAMS_ERROR);
        }
        //查出数据
        Picture oldPicture = this.lambdaQuery().eq(Picture::getId, pictureEditRequest.getId()).one();
        if(oldPicture==null){
            throw new bizException(-1,"没有这张图片");
        }
        //校验数据
        this.checkPictureAuth(loginUser, oldPicture);
        Picture picture=new Picture();
        BeanUtils.copyProperties(pictureEditRequest,picture);
        //将传来的tags转换为json
        String tags = JSONUtil.toJsonStr(pictureEditRequest.getTags());
        picture.setTags(tags);
        //设置编辑时间
        picture.setEditTime(LocalDateTime.now());
        //填充审核信息
        this.fillReviewParams(picture,loginUser);
        //修改数据库
        boolean update = this.updateById(picture);
        ThrowUtils.throwIf(!update,ErrorCode.SYSTEM_ERROR);
    }
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, LoginUserVO loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"该空间不存在");
        if(!space.getUserId().equals(loginUser.getId())){
            throw new bizException(ErrorCode.NO_AUTH_ERROR);
        }
        // 3. 查询该空间下所有图片（必须有主色调）
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if(CollUtil.isEmpty(pictureList)){
            return null;
        }
        // 将目标颜色转为 Color 对象
        Color picColordecode = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<Picture> pictures = pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
            // 提取图片主色调
            String picturePicColor = picture.getPicColor();
            // 没有主色调的图片放到最后
            if (StrUtil.isBlank(picturePicColor)) {
                return Double.MAX_VALUE;
            }
            Color colorDecode = Color.decode(picturePicColor);
            return ColorSimilarUtils.calculateSimilarity(picColordecode, colorDecode);
            // 取前 12 个
        })).limit(12).collect(Collectors.toList());
        // 转换为 PictureVO
        return pictures.stream().map(PictureVO::objToVo).collect(Collectors.toList());
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, LoginUserVO loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String nameRule = pictureEditByBatchRequest.getNameRule();
        // 1. 校验参数
        ThrowUtils.throwIf(pictureIdList == null || pictureIdList.isEmpty(), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId==null,ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR);
        if(!space.getUserId().equals(loginUser.getId())){
            throw new bizException(ErrorCode.NO_AUTH_ERROR);
        }
        // 3. 查询指定图片，仅选择需要的字段
        List<Picture> pictures = this.lambdaQuery().select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if(CollUtil.isEmpty(pictures)){
            return;
        }
        // 4. 更新分类和标签
        pictures.forEach(picture -> {
            if(category!=null){
                picture.setCategory(category);
            }
            if(tags!=null){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        //批量修改名称
        if(nameRule!=null){
            this.fillPictrueWithNameRole(nameRule,pictures);
        }
        // 5. 批量更新
        boolean result = this.updateBatchById(pictures);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR);
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    @Override
    public void fillPictrueWithNameRole(String nameRule,List<Picture> pictureList) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new bizException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, LoginUserVO loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = this.getById(pictureId);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 权限校验
        this.checkPictureAuth(loginUser, picture);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input=new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtils.copyProperties(createPictureOutPaintingTaskRequest,taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

}
